import config from './config';
import { getCookie, delCookie, getLocalStorage } from './cookieHelper';

// Auth
export function getAuthHeader(sso_token) {
  return ({
    headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + sso_token,
      'Content-Type': 'application/json',
    },
  });
}

export function redirectLogin() {
  localStorage.clear();
  window.location.href = config.redirectUrl;
}

export function authenticated() {
  const sso_token = getLocalStorage("user");
  if (!sso_token) {
    redirectLogin();
  }
}

export function logOut() {
  delCookie({
    name: 'sso_token',
    path: '/',
    domain: 'http://localhost:8000/',
  });
  authenticated();
}
// 路由拦截处理
export function onRouteEnter({ location }, replaceState) {
  if ('-'+typeof localStorage !='-'+undefined) {
    // 获取本地存储的用户权限
    var power = getLocalStorage('power');
    let flag = false;
    power.forEach(item => {
      item.children.forEach(child => {
        if (child.url === location.pathname || location.pathname === '/') {
          flag = true;
        }
      });
    });
    if(!flag){
      // 如果未授权则跳转
      window.location.href = '/403';
    }
  }
}